	var rootPath = getRootPath();
/**
 * 养修预约画面JS
 */
$(document).ready(function(){

	var openId = getQueryParamValue("openId");
	var result = getCookie("WECHAT_USER_OPENID");
	if(result==null){
	  // alert('openId 不存在!');
	  setCookie("WECHAT_USER_OPENID",openId);
	  // location.reload();
	}else{
		// alert(result);
	}
		$("#KmFirst").hide();
		var mileageHtml = '';
		// 里程
		for(var i=5000;i<300001;){
			// options.push("<option name='"+i+"公里'
			// value='"+i+"'>"+i+"公里</option>");
			mileageHtml = mileageHtml + '<a class="list-group-item" onclick="addMileage('+i+')">'+i+'公里'
									  + '</a>'
			i=i+5000;
		}
		$("#mileage").append(mileageHtml);
		
		// 监听城市选择页面搜索输入框
		$("#cha").keyup(function(event){ 
			if (event.keyCode === 13){ 
			searchCity();
			} 
		}); 

		
		// 监听经销商选择页面搜索输入框
		$("#sou").keyup(function(event){ 
	        if (event.keyCode === 13){ 
	       	 searchDealer();
	        } 
	      }); 
	var d = new Date();
 	var maintainDay = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
	var bookingType = $("#maintainType").val();
	var rootPath = getRootPath();
	
	//
	$.ajax({
		headers: {'Cookie' : document.cookie },
		method : 'get',
		url : rootPath+'/customer/api/v1/queryUserOwner',
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			alert("数据刷新失败");
		},
		success : function(resultData){ 
			if(resultData.length==0){
				// 粉丝
				alert("请先注册会员再使用");
				// window.location = rootPath + "/views/homepage/signUp.html";
				window.location = rootPath + "/views/modules/register.html";
			}else{
				// 会员
				$.ajax({
					headers: {'Cookie' : document.cookie },
					method : 'get',
					url : rootPath+'/maintain/api/v1/maintainSel',
					error:function(XMLHttpRequest, ajaxOptions, thrownError){
						// alert("未连接服务器!");
					},
					success : function(resultData){
						if(resultData.length==0){
							alert("请先绑定车辆！");
							window.location = rootPath + "/views/homepage/Authentication.html";
						}else{			
							var wholeHtml = '';
						$.each(resultData,function(maintainSelIndex,maintainSelObj){
							var dealerName = maintainSelObj.dealerName;
							var detailAddress = maintainSelObj.detailAddress;
			// liyhi 2017-04-01 该需求，把车牌号改成车系
			// var licenseNo = maintainSelObj.licenseNo;
							var licenseNo = maintainSelObj.seriesName;
							var modelName = maintainSelObj.modelName;
							var phone = maintainSelObj.phone;
							var vin = maintainSelObj.vin;
							$("#dealerName").html(dealerName);
							$("#detailAddress").html(detailAddress);
							$("#licenseNo").html(licenseNo);
							$("#moName").html(modelName);
							$("#modelName").val(modelName);
							$("#phone").val(phone);
							$("#vin").val(vin);
							$("#dealerCode").val(maintainSelObj.dealerCode);
							$("#openId").val(maintainSelObj.openId);
							$("#userId").val(maintainSelObj.userId);
							if(maintainSelObj.saleName!=""||maintainSelObj.saleName!=null){
								$("#Counselor").html(maintainSelObj.saleName);
								$("#salesConsultantId").val(maintainSelObj.saleId);
							}
						});
					  }
			
					}
				});
			}
		}
	});
	
	
	
	
	// 养修预约的主DIV展现
	$("#maintainMainDiv").addClass("active in");
	
	
	// 临时改动显示
	// $("#maintainDateSelDiv").show().addClass("active in");
	// end
	
	
	// 经销商代码
	var dealerCode = getQueryParamValue("dealerCode");
	// 品牌代码
	var brandCode = getQueryParamValue("brandCode");
	// 服务顾问
	var serviceAdvisorCode = getQueryParamValue("serviceAdvisorCode");
	var openId = getQueryParamValue("openId");
	
	// 给hidden变量赋值
	if (openId!=null && openId != ''){
		$("#openId").val = openId;
	}
	if (dealerCode!=null && dealerCode != ''){
		$("#dealerCode").val = dealerCode;
	}
	if (brandCode!=null && brandCode != ''){
		$("#brandCode").val = brandCode;
	}
	if (serviceAdvisorCode!=null && serviceAdvisorCode != ''){
		$("#serviceAdvisorCode").val = serviceAdvisorCode;
	}
	
	
	// 校验输入
	function checkInput(){
		if(!$("#dealerCode").val()){
			alert("请选择销售店")
			return false;
		}
// if(!$("#vin").val()){
// alert("未找到车辆信息")
// return false;
// }
		if(!$("#appointType").val()){
			alert("请选择预约类型")
			return false;
		}
		if(!$("#maintainDate").val()){
			alert("请选择预约到店日期")
			return false;
		}
		if(!$("#maintainTime").val()){
			alert("请选择预约到店时间")
			return false;
		}
// if(!$("#MaintainKM").val()){
// alert("请选择预约保养公里数")
// return false;
// }
// if(!$("#phone").val()){
// alert("未找到手机号")
// return false;
// }
		
		return true;
		
	}
	


	// 预约确定按钮
	$("#immediatelyAppoint").click(function(){
		// alert("hello");
		// liyh1 2017-04-07 添加加载层 并 灰色按钮
		layer.load(1,{shade:false});
		$("#immediatelyAppoint").attr("disabled","disabled");
		$("#immediatelyAppoint").attr("class","btnbtn1");
		// layer.load(1,{shade:false});
		var counselorPhone = $("#salesConsultantId").val();
		var counselorName = $("#Counselor").html();
		 
		if(counselorPhone!=undefined && counselorPhone!=''){
			var salesConsultantPhone = counselorPhone;
		}
		if(counselorName!=undefined && counselorName!=''){
			var salesConsultantName = counselorName;
		}
		
		if(!checkInput()){
			$("#immediatelyAppoint").removeAttr("disabled");
			$("#immediatelyAppoint").attr("class","btnbtn");
			layer.closeAll('loading');
			return false;
		}

		
		var maintainDto ={"dealerCode":$("#dealerCode").val(),"vin":$("#vin").val(),"appointType":$("#appointType").val(),"reseApplStartTime":$("#maintainDate").val()+" "+$("#maintainTime").val()+":00",
				"mileage":$("#MaintainKM").val(),"phone":$("#phone").val(),"salesConsultantId":$("#salesConsultantId").val(),"sourceType":$("#sourceType").val(),"modelName":$("#modelName").val(),
				"salesConsultantPhone":salesConsultantPhone,"salesConsultantName":salesConsultantName,"appointTypeName":$("#appointTypeName").val(),"remarks":$("#remarks").val(),
				"openId":$("#openId").val()
		};
	$.ajax({
		headers: {'Cookie' : document.cookie }, 
        type:"POST", 
        url:rootPath+"/maintain/api/v1/saveMaintain", 
        dataType:"json",      
        contentType:"application/json",               
        data:JSON.stringify(maintainDto), 
        success:function(data){ 
        	if(data.errorCode=="0"){
        		$('#sureModal').modal({
    				keyboard: false,
    				backdrop:false
    			}); 
        		layer.closeAll('loading');
        	}else{
        		$("#immediatelyAppoint").removeAttr("disabled");
        		alert(data.errorMsg);
        		layer.closeAll('loading');
        		return false;
        	}
        },
        error:function(data){
        	layer.closeAll('loading');
        	// alert("预约失败！");
        }
     });
	layer.closeAll('loading');
	});
	

	// 选择日期时间
    var now = new Date();
    var currYear = now.getFullYear();	
    // 选择日期
    $('#maintainDateSelectText').mobiscroll().date({
        theme: 'ios',
        lang: 'zh',
        display: 'bottom',
        mode: 'datetimeDate',
        min: new Date(now.getFullYear(), now.getMonth(), now.getDate()),
        startYear: currYear,
        dateFormat:'yyyy-mm-dd'
    
    });
    
  
    
    $('.calendar td').click(function(){
    	layer.msg('正在查询可预约到店时间',{icon:16,shade:[0.3,'#000']});
    	var $this = $(this);
    	var _date = $this.attr('data');
    	if(typeof _date !== 'undefined'){
    		var _formatDate = _date.substring(0,4)+'-'+_date.substring(4,6)+'-'+_date.substring(6,8);
        	getMaintainTimeData(_formatDate);
    	}
    	
    })
    
});
// 定位所在地经销商,点击
function selectNowDealer(obj){
	$("#sou").val("");
	$("#firstImg").hide();
	 $("#maintainMainDiv").hide();
	 $("#maintainMainDiv").removeClass("active in");
	 $("#maintainDealerDiv").hide();
	 $("#maintainDealerDiv").removeClass("active in");
	 $("#maintainDateSelDiv").hide();
	 $("#maintainDateSelDiv").removeClass("active in");
	 $("#nowDealerDiv").show();
	 $("#dealerDiv").html("");
	 // 初始化界面
	 $("#nowDealerDiv").addClass("active in");
		// 根据编号获取所在地经销商列表
			$.ajax({
				headers: {'Cookie' : document.cookie },
				method : 'get',
				url : rootPath+'/maintain/api/v1/maintainDealers?regionName='+ $("#regionName").val()+'&dealerCode='+$("#dealerCode").val(),
				error:function(XMLHttpRequest, ajaxOptions, thrownError){
					// alert("未连接服务器!");
				},
				success : function(resultData){
					
					var wholeHtml = '';
					var  Km = '';
					$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
						
						var findDealerHtml = '';
						var lat1 = maintainDealerObj.latitude;
						var lng1 = maintainDealerObj.longitude;
						var lat2 = $("#latitude").val();
						var lng2 = $("#longitude").val();
						Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
						if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
						else{var distance = Km + '千米';}
						
							if(maintainDealerObj.remark =='首选店'){
								$("#KmFirst").show();
								$("#nameFirst").html(maintainDealerObj.dealerShortName);
								$("#distanceFirst").html(distance);
								$("#addrFirst").html(maintainDealerObj.detailAddress);
								$("#codeFirst").val(maintainDealerObj.dealerCode);
								$('#Tel').attr('href','tel:'+maintainDealerObj.serviceHotline);
								$("#remarkFirst").html(maintainDealerObj.remark);
							}else{
						findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'" style="margin: 0px;padding: 3px;">'
														+ '<div class="panel panel-default">'
														+ '<table style="width:100%" class="table-condensed"><tbody>'
														+ '<tr>'
														+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
														+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerShortName + '</p>'
														+ '</a></td>'
														+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a"><a onclick="sureDealer('+maintainDealerIndex+')">'
														+ '<span>距离：</span><span>'+ distance + '</span>'
														+ '</a></td>'
														+ '</tr><tr>'
														+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
														+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
														+ '</a></td>'
														+ '<td style="width:100px;text-align:center;">'
														+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
														+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
														+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
														+ '</a></td>'
														+ '</tr>'
														+ '</tbody></table>'
														+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
														+ '</div></li>'
						
						wholeHtml += findDealerHtml;
						}
					});
					$("#dealerDiv").append(wholeHtml);
				}
			});
			
}
// 选择经销商，点击
function selectMaintainDealer(obj){
	$("#cha").val("");
	$("#dealerMap").show();
	$("#KmFirst").hide();
	$("#firstImg").hide();
	$("#maintainMainDiv").hide();
	$("#maintainMainDiv").removeClass("active in");
	$("#maintainDateSelDiv").hide();
	$("#maintainDateSelDiv").removeClass("active in");
	$("#nowDealerDiv").hide();
	$("#nowDealerDiv").removeClass("active in");
	 $("#maintainDealerDiv").show();
	 // 初始化界面
	 $("#maintainDealerDiv").addClass("active in");
		
		// 选择经销商城市信息取得。
		$.ajax({
			headers: {'Cookie' : document.cookie },
			method : 'get',
			url : rootPath+'/maintain/api/v1/maintainDealerMap?regionType=90011002',
			error:function(XMLHttpRequest, ajaxOptions, thrownError){
				// alert("获取失败!");
			},
			success : function(resultData){

				var wholeHtml = '';
				
				var city = '';
				$.each(resultData,function(maintainDealerMapIndex,maintainDealerMapObj){
					var DealerMapHtml = '';
					var str = maintainDealerMapObj.regionName;
					if(str == "") return;
					var arr = maintainDealerMapObj.aleph;
					for(var i=0;i<26;i++){
						var en = String.fromCharCode((97+i));
						if(arr == en){
							city = maintainDealerMapObj.regionName;

							DealerMapHtml = DealerMapHtml + '<li>'
														  + '<a onclick="selectDealer('+ maintainDealerMapIndex +')">'
														  + '<span style="font-size:18px;color:#7a7a7a">' + city + '</span>'
														  + '<input type="hidden" id="'+maintainDealerMapIndex + '" value="'+ maintainDealerMapObj.regionName +'">'
														  + '</a>'
														  + '</li>'
														  + '<div style="height:1px;margin:0px auto;padding:0px;background-color:#F4F4F4;overflow:hidden;"></div>'
							
							$("#"+en).append(DealerMapHtml);
						}
					}
				});

			}
		});
		
}

// 20170613-up-wdf

function getMaintainTimeData(_time){
	// 获取所有的时间列表
	$("#timeSelectRadioGroup").html("");
	//获取所有的时间列表
	$.ajax({
		headers: {'Cookie' : document.cookie },
		type:"GET", 
        url:rootPath+"/maintain/api/v1/simple?dealerCode="+$("#dealerCode").val(), 
        dataType:"json",      
        async: false,
        contentType:"application/json",               
        data:null, 
        success:function(data){
        	//alert(data);
        	//alert(eval(data));
			var appendRadioStr = "";//"<div class='btn-group'  data-toggle='buttons'>";
			$.each(data,function(stationIndex,stationStr){
				if(stationStr>'12'){
					appendRadioStr += "<button type='button' class='btn btn-default btn-sm btpm' value='"+ stationStr +"' style='display:none;' onclick='free(this.value)'>"+stationStr+"</button>"
    				
				}else{
					appendRadioStr += "<button type='button' class='btn btn-default btn-sm btam' value='"+ stationStr +"' style='display:block;' onclick='free(this.value)'>"+stationStr+"</button>"
    				
				}
					
			});
			$("#timeSelectRadioGroup").empty().append(appendRadioStr);
			$("#am").trigger('click');
			
        },
        error:function(data){
        	alert("刷新时间失败");
        }
     });
}

// ---end---

// 选择养修预约时间，点击
function selectMaintainTime(obj){
	if(!$("#dealerCode").val()){
		alert("请先选择销售店")
		return false;
	}
	
	$("#timeSelectRadioGroup").html("");
	
	
	 $("#maintainMainDiv").hide();
	 $("#nowDealerDiv").hide();
	 $("#maintainDealerDiv").hide();
	 $("#maintainMainDiv").removeClass("active in");
	 $("#maintainDateSelDiv").show();
	 // 初始化界面
	 $("#maintainDateSelectText").val("");
	 $("#maintainTimeSelectLabel").html("");
	 $("#maintainDateSelDiv").addClass("active in");
	 
}

// 选择保养日期，时间之后确认
function confirmMaintainTime(obj) {
	if($("#day").html()==""){
		alert("未选择日期")
		return false;
	}
	if($("#time").html()==""){
		alert("未选择时间")
		return false;
	}
	
	var chooseDateString= $("#day").html()+" "+$("#time").html()+":00";
	var chooseDate = Date.parse(new Date(chooseDateString));// 选择的时间戳
	var timestamp = Date.parse(new Date());// 当前的时间戳
	if(timestamp>chooseDate){
		alert("请选择晚于当前时间的预约时间！");
		return false;
	}
	
	

	$("#selectMaintainTimeSpan").val("#ss").val();
	$("#maintainMainDiv").show();
	$("#maintainMainDiv").addClass("active in");
	$("#maintainDateSelDiv").removeClass("active in");
	$("#maintainDateSelDiv").hide();
	
	$("#selectMaintainTimeLink").html($("#day").html()+$("#time").html());
	$("#maintainDate").val($("#day").html());
	$("#maintainTime").val($("#time").html());
}

function closeMaintainTime(obj) {
	$("#selectMaintainTimeSpan").val("#ss").val();
	$("#maintainMainDiv").show();
	$("#maintainMainDiv").addClass("active in");
	$("#maintainDateSelDiv").removeClass("active in");
	$("#maintainDateSelDiv").hide();
}

/**
 * 跳转到绑定车辆页面
 * 
 * @returns
 */
function to_bingCar(){
	
	window.location = rootPath + "/views/vehicleBinding/vehicleBinding.html";
}
/**
 * 跳转到预约详情页面
 * 
 * @returns
 */
function re(){
	window.location = rootPath + "/views/modules/maintenance.html";
}

function free(val){
	  var free = val;
	  $("#time").html(val);
}

// 进行经纬度转换为距离的计算

function Rad(d){
  return d * Math.PI / 180.0;// 经纬度转换成三角函数中度分表形式。
}
// 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function GetDistance(lat1,lng1,lat2,lng2){

   var radLat1 = Rad(lat1);
   var radLat2 = Rad(lat2);
   var a = radLat1 - radLat2;
   var  b = Rad(lng1) - Rad(lng2);
   var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
   Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
   s = s *6378.137 ;// EARTH_RADIUS;
   s = Math.round(s * 10000) / 10000; // 输出为公里
   // s=s.toFixed(4);
   return s;
}
function selectDealer(obj){
	$("#sou").val("");
	var code = $("#"+obj).val();
	$("#regionName").val(code);
	$("#firstImg").hide();
	$("#maintainMainDiv").hide();
	$("#maintainMainDiv").removeClass("active in");
	$("#maintainDealerDiv").hide();
	$("#maintainDealerDiv").removeClass("active in");
	$("#maintainDateSelDiv").hide();
	$("#maintainDateSelDiv").removeClass("active in");
	$("#dealerDiv").html("");
	 $("#nowDealerDiv").show();
	 $("#searchCity").html("");
	 $("#searchDealer").html("");
	 $("#list2").show();
	 // 初始化界面
	 $("#nowDealerDiv").addClass("active in");
	 for(var i=0;i<26;i++){
			var en = String.fromCharCode((65+i));
			$("#"+en).html("");
	 }
	// 根据编号获取所在地经销商列表
	$.ajax({
		headers: {'Cookie' : document.cookie },
		method : 'get',
		url : rootPath+'/maintain/api/v1/maintainDealers?regionName='+code+'&dealerCode='+$("#dealerCode").val(),
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			// alert("未连接服务器!");
		},
		success : function(resultData){
			
			var wholeHtml = '';
			var  Km = '';
			$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
				
				var findDealerHtml = '';
				var lat1 = maintainDealerObj.latitude;
				var lng1 = maintainDealerObj.longitude;
				var lat2 = $("#latitude").val();
				var lng2 = $("#longitude").val();
				Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
				if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
				else{var distance = Km + '千米';}
				
					if(maintainDealerObj.remark =='首选店'){
						$("#KmFirst").show();
						$("#nameFirst").html(maintainDealerObj.dealerShortName);
						$("#distanceFirst").html(distance);
						$("#addrFirst").html(maintainDealerObj.detailAddress);
						$("#codeFirst").val(maintainDealerObj.dealerCode);
						$('#Tel').attr('href','tel:'+maintainDealerObj.serviceHotline);
						$("#remarkFirst").html(maintainDealerObj.remark);
					}else{
				findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'" style="margin: 0px;padding: 3px;">'
												+ '<div class="panel panel-default">'
												+ '<table style="width:100%" class="table-condensed"><tbody>'
												+ '<tr>'
												+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
												+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerShortName + '</p>'
												+ '</a></td>'
												+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a"><a onclick="sureDealer('+maintainDealerIndex+')">'
												+ '<span>距离：</span><span>'+ distance + '</span>'
												+ '</a></td>'
												+ '</tr><tr>'
												+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
												+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
												+ '</a></td>'
												+ '<td style="width:100px;text-align:center;">'
												+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
												+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
												+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
												+ '</a></td>'
												+ '</tr>'
												+ '</tbody></table>'
												+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
												+ '</div></li>'
				
				wholeHtml += findDealerHtml;
				}
			});
			$("#dealerDiv").append(wholeHtml);
		}
	});
}
function sureDealer(obj){
	if(obj=='-1'){
		  var code = $("#codeFirst").val();
	 	  var name = $("#shortNameFirst").html();
	   	  var addr = $("#addrFirst").html();
		}else{
		  var code = $("#code"+obj).val();
		  var name = $("#name"+obj).html();
		  var addr = $("#addr"+obj).html();
		}
	// alert(code+','+name+','+addr);
	$("#dealerCode").val(code);
	$("#dealerName").html(name);
	$("#detailAddress").html(addr);
	$("#nowDealerDiv").hide();
	$("#nowDealerDiv").removeClass("active in");
	 $("#maintainMainDiv").show();
	 // 初始化界面
	 $("#maintainMainDiv").addClass("active in");
	 $("#firstImg").show();
	 $("#list2").show();
	 $("#selectMaintainTimeLink").html("选择到店时间");
	 $("#searchDealer").html("");
}

// 关闭选择经销商的div
function closeSureDealer(obj){
	$("#searchDealer").html("");
	$("#nowDealerDiv").hide();
	$("#nowDealerDiv").removeClass("active in");
	 $("#maintainMainDiv").show();
	// 初始化界面
	 $("#maintainMainDiv").addClass("active in");
	 $("#firstImg").show();
	 $("#list2").show();
}



// 排序
function Sort(bo)
{
    var arr = document.getElementById("list2").innerHTML.match(/<li>[\s\S]+?<\/li>/g);
    arr.sort(function(a,b){
        a = parseInt(/\d+/.exec(a)[0], 10);
        b = parseInt(/\d+/.exec(b)[0], 10);
        return bo?b-a:a-b;
    });
    document.getElementById("ol1").innerHTML = arr.join("");
}

// 服务顾问选择
function selectCounselor(){
	
	if(!$("#dealerCode").val()){
		alert("请先选择销售店")
		return false;
	}
	
	$("#seviceUser").html("");
	// 服务顾问信息取得
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/customer/api/v1/counselors?positionId=602&dealerCode="+$("#dealerCode").val(), 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '';
			$.each(data,function(carModelIndex,advisersObj){
				var counselorsHtml = '';
				
				counselorsHtml = counselorsHtml + '<a class="list-group-item" onclick="addCounseor('+carModelIndex+')">'
												+ advisersObj.userName
												+ '<input class="hidden" type="text" id="coun'+carModelIndex+'" value="'+advisersObj.userName+'">'
												+ '<input class="hidden" type="text" id="salePhone'+carModelIndex+'" value="'+advisersObj.phone+'">'
												+ '<input class="hidden" type="text" id="saleUserId'+carModelIndex+'" value="'+advisersObj.userId+'">'
												+ '</a>'
// counselorsHtml = counselorsHtml + '<div class="radio"
// onclick="addCounseor('+carModelIndex+')">'
// + '<label>'
// + '<input name="SelRadio" type="radio" id="coun'+carModelIndex+'"
// value="'+advisersObj.userName+'">'+advisersObj.userName
// + '<input class="hidden" type="text" id="salePhone'+carModelIndex+'"
// value="'+advisersObj.phone+'">'
// + '<input class="hidden" type="text" id="saleUserId'+carModelIndex+'"
// value="'+advisersObj.userId+'">'
// + '</label>'
// + '</div>'

				wholeHtml += counselorsHtml;								
			});
			
			if(wholeHtml=='') wholeHtml = '<div style="text-align:center;color:#b09893;">暂无数据！</div>';
			$("#seviceUser").append(wholeHtml);
	    },
	    error:function(data){
	    	// alert("数据刷新失败，请联系管理员！");
	    }
	 });
	
	$('#counselorModal').modal({
	});
};
function addCounseor(obj){
	// alert(obj);
	$("#salesConsultantPhone").val($("#salePhone"+obj).val());
	$("#salesConsultantId").val($("#saleUserId"+obj).val());
	// $("#Counselor").html($("#seviceUser").find("option:selected").attr("userName"));
	$("#Counselor").html($("#coun"+obj).val());
	$("#conselorBtn").click();
};
// 当前里程
function selectMileage(){
	$('#MileageModal').modal({
	});
};
function addMileage(i){
	$("#Mileage").html(i+'公里');
	$("#MaintainKM").val(i);
	$("#MileageBtn").click();
};
// 预约类型
function selectMtType(){
	$('#MtTypeModal').modal({
	});
};
function addMtType(obj){
	$("#appointType").val(obj);
	$("#MtType").html($("#mtType"+obj).val());
	$("#MtTypeBtn").click();
};
// 搜索城市
function searchCity(){
	$("#dealerMap").hide();
	$("#searchCity").html("");
	var regionName = $("#cha").val();
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/maintain/api/v1/maintainSelectCity?regionName="+regionName, 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '<ul class="list-group">';
			
			$.each(data,function(maintainSearchCityIndex,maintainSearchCityObj){
				var DealerMapHtml = '';
				
					DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
													+ '<a onclick="selectDealer('+ maintainSearchCityIndex +')">'
													+ '<span style="font-size:18px;color:#7a7a7a">' + maintainSearchCityObj.regionName + '</span>'
													+ '<input type="hidden" id="'+maintainSearchCityIndex + '" value="'+ maintainSearchCityObj.regionName +'">'
													+ '</a>'
													+ '</li>'		
				       wholeHtml += DealerMapHtml;
			});
			wholeHtml = wholeHtml + '</ul>'
			$("#searchCity").append(wholeHtml);
	    },
	    error:function(data){
	    	// alert("数据刷新失败，请联系管理员！");
	    }
	 });
}
// 搜索经销商
function searchDealer(){
	$("#list2").hide();
	$("#searchDealer").html("");
	var dealerName = $("#sou").val();
	var regionName = $("#regionName").val();
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/maintain/api/v1/searchDealers?dealerName="+dealerName, 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '<ul class="list-group">';
			var  Km = '';
			$.each(data,function(SearchDealerIndex,SearchDealerObj){
				var DealerMapHtml = '';
				var findDealerHtml = '';
				var lat1 = SearchDealerObj.latitude;
				var lng1 = SearchDealerObj.longitude;
				var lat2 = $("#latitude").val();
				var lng2 = $("#longitude").val();
				Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
				if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
				else{var distance = Km + '千米';}
				
					DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
													+ '<table style="width:100%" class="table-condensed"><tbody>'
													+ '<tr>'
													+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+SearchDealerIndex+')">'
													+ '<p id="name'+ SearchDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + SearchDealerObj.dealerShortName + '</p>'
													+ '<p class="hidden" id="shortName'+SearchDealerIndex+'">'+SearchDealerObj.dealerShortName+'</p>'
													+ '</a></td>'
													+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a"><a onclick="sureDealer('+maintainDealerIndex+')">'
													+ '<span>距离：</span><span>'+ distance + '</span>'
													+ '</a></td>'
													+ '</tr><tr>'
													+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
													+ '<span id="addr'+ SearchDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + SearchDealerObj.detailAddress + '</span>'
													+ '</a></td>'
													+ '<td style="width:100px;text-align:center;">'
													+ '<a href="tel:'+ SearchDealerObj.serviceHotline +'" id="Tel">'
													+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
													+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
													+ '</a></td>'
													+ '</tr>'
													+ '</tbody></table>'
													+ '<input id="code'+ SearchDealerIndex +'" class="hidden" value="' + SearchDealerObj.dealerCode + '">'
													+ '</li>'
											
					wholeHtml += DealerMapHtml;
			});
			wholeHtml = wholeHtml + '</ul>'
			$("#searchDealer").append(wholeHtml);
	    },
	    error:function(data){
	    	// alert("数据刷新失败，请联系管理员！");
	    }
	 });
}
function getCookie(cookie_name) {
	var allcookies = document.cookie;
	var cookie_pos = allcookies.indexOf(cookie_name);

	// 如果找到了索引，就代表cookie存在，
	// 反之，就说明不存在。
	if (cookie_pos != -1) {
		// 把cookie_pos放在值的开始，只要给值加1即可。
		cookie_pos += cookie_name.length + 1;
		var cookie_end = allcookies.indexOf(";", cookie_pos);

		if (cookie_end == -1) {
			cookie_end = allcookies.length;
		}

		var value = unescape(allcookies.substring(cookie_pos, cookie_end));
	}

	return value;
}
function setCookie(name,value)
{
    var Days = 1;
    var exp  = new Date(); 
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
	// alert(document.cookie);
}